//
//  JYJVCOfRegister.m
//  HappyListen
//
//  Created by 冀永金 on 16/8/27.
//  Copyright © 2016年 冀永金. All rights reserved.
//

#import "JYJVCOfRegister.h"
#import "Masonry.h"
#import "BaseButton.h"
#import "JYJVCOfSetPassword.h"
#import "JYJNetWorkParser.h"
#import "JYJTAMacro.h"
#import "JYJMusicMiniView.h"
#define STR1  @"json=%7B%22phone%22%3A%22";
#define STR3  @"%22%2C%22isJoin%22%3A1%7D";
#define COMMA_idcodeSTR @"%22%2C%22idcode%22%3A%22"
#define URL @"http://www.aiyinsitanfm.com/mobile/user/reqcode.jhtml"

@interface JYJVCOfRegister ()
@property (nonatomic, strong) UITextField *textFieldOfPhone;
@property (nonatomic, strong) UITextField *textOfSecurityCode;
@property (nonatomic, strong) UIButton *button;
@end

@implementation JYJVCOfRegister
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"注册";
    self.view.backgroundColor = [UIColor colorWithRed:0.09 green:0.09 blue:0.11 alpha:1.00];
    [self configSubViews];
     self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    //json={"phone":"15567471591","isJoin":1}
    // Do any additional setup after loading the view.
}
- (void)configSubViews {
    self.textFieldOfPhone = [[UITextField alloc]init];
    _textFieldOfPhone.placeholder = @"手机号码";
    _textFieldOfPhone.backgroundColor = [UIColor colorWithRed:0.07 green:0.07 blue:0.08 alpha:1.00];
    [self.view addSubview:_textFieldOfPhone];
    _textFieldOfPhone.textColor = [UIColor  whiteColor];
    // 设置placeholder的字体颜色
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[NSForegroundColorAttributeName] = [UIColor whiteColor];
    NSAttributedString *attribute = [[NSAttributedString alloc] initWithString:_textFieldOfPhone.placeholder attributes:dic];
    [_textFieldOfPhone setAttributedPlaceholder:attribute];
    [_textFieldOfPhone mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).with.offset(20);
        make.left.equalTo(self.view.mas_left).with.offset(5);
        make.right.equalTo(self.view.mas_right).with.offset(-5);
        make.height.mas_equalTo(50);
    }];
    
    self.textOfSecurityCode = [[UITextField alloc]init];
    _textOfSecurityCode.placeholder = @"短信验证码";
    _textOfSecurityCode.backgroundColor = [UIColor colorWithRed:0.07 green:0.07 blue:0.08 alpha:1.00];
    _textOfSecurityCode.textColor = [UIColor whiteColor];
    // 设置placeholder的字体颜色
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[NSForegroundColorAttributeName] = [UIColor whiteColor];
    NSAttributedString *attributeSe = [[NSAttributedString alloc] initWithString:_textOfSecurityCode.placeholder attributes:dict];
    [_textOfSecurityCode setAttributedPlaceholder:attributeSe];
    [self.view addSubview:_textOfSecurityCode];
    [_textOfSecurityCode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_textFieldOfPhone.mas_bottom).with.offset(2);
        make.left.equalTo(self.view.mas_left).with.offset(5);
        make.right.equalTo(self.view.mas_right).with.offset(-5);
        make.height.mas_equalTo(50);
    }];
    self.button = [UIButton buttonWithType:UIButtonTypeSystem];
    [_button setTitle:@"获取短信验证码" forState:UIControlStateNormal];
    [_button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [self.view addSubview:_button];
    _button.titleLabel.font = [UIFont systemFontOfSize:18];
    [_button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).with.offset(25);
        make.right.equalTo(self.view.mas_right).with.offset(-5);
        make.width.mas_equalTo(150);
        make.height.mas_equalTo(45);
    }];
    _button.layer.cornerRadius = 10;
    _button.clipsToBounds = YES;
    [_button addTarget:self action:@selector(handleCode:) forControlEvents:UIControlEventTouchUpInside];
    [_button.layer setBorderWidth:2];
    [_button.layer setBorderColor:[UIColor cyanColor].CGColor];
    BaseButton *buttonOfSubmit = [BaseButton buttonWithType:UIButtonTypeSystem];
    [buttonOfSubmit setTitle:@"提交" forState:UIControlStateNormal];
    buttonOfSubmit.backgroundColor = [UIColor redColor];
    [buttonOfSubmit setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:buttonOfSubmit];
    [buttonOfSubmit mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_button.mas_bottom).with.offset(150);
        make.left.equalTo(self.view.mas_left).with.offset(20);
        make.right.equalTo(self.view.mas_right).with.offset(-20);
        make.height.mas_equalTo(50);
    }];
    buttonOfSubmit.layer.cornerRadius = 20;
    buttonOfSubmit.clipsToBounds = YES;
    [buttonOfSubmit addTarget:self action:@selector(handleNext:) forControlEvents:UIControlEventTouchUpInside];

}
- (void)handleNext:(BaseButton *)button {
    NSString *str1 = STR1;
    NSString *str3 = COMMA_idcodeSTR;
    NSString *string = [NSString stringWithFormat:@"%@", self.textFieldOfPhone.text];
    NSString *str4 = [NSString stringWithFormat:@"%@",self.textOfSecurityCode.text];
    NSString *str5 = BRACKETS_STR;
    string = [[[[str1 stringByAppendingString:string] stringByAppendingString:str3] stringByAppendingString:str4] stringByAppendingString:str5];
       [JYJNetWorkParser POST:@"http://www.aiyinsitanfm.com/mobile/user/checkcode.jhtml" andBody:string andBodyStyle:JYJBodyString andHeader:HEADDIC andResponse:JYJJSON andSuccessBlock:^(id result) {
        NSDictionary *status = [result objectForKey:@"status"];
        NSNumber *succed =[status objectForKey:@"succeed"] ;
        if ([succed isEqualToNumber:@1]) {
            self.tabBarController.tabBar.hidden = YES;
            self.hidesBottomBarWhenPushed = YES;
            JYJVCOfSetPassword *passWord = [[JYJVCOfSetPassword alloc]init];
            [self.navigationController pushViewController:passWord animated:YES];
            passWord.userName = self.textFieldOfPhone.text;
            self.hidesBottomBarWhenPushed = NO;
            
        }else {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入正确的验证码" preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alert animated:YES completion:nil];
            [alert dismissViewControllerAnimated:YES completion:nil];
        }
        
    } andFailureBlock:^(NSError *error) {
        
    }];

}
- (void)handleCode:(UIButton *)button {
    NSString *str1 =STR1;
    NSString *str3 = STR3;
    NSString *string = [NSString stringWithFormat:@"%@", self.textFieldOfPhone.text];
    string = [[str1 stringByAppendingString:string] stringByAppendingString:str3];
    
    BOOL isPhoneNum = [self isMobileNumber:self.textFieldOfPhone.text];
    if (isPhoneNum == 1) {
        [JYJNetWorkParser POST:URL andBody:string andBodyStyle:JYJBodyString andHeader:HEADDIC andResponse:JYJJSON andSuccessBlock:^(id result) {
            NSDictionary *status = [result objectForKey:@"status"];
            NSNumber *succed =[status objectForKey:@"succeed"] ;
            if ([succed isEqualToNumber:@1]) {
                [self receiveCheckNumButton];
                
            }else {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"该手机号码已经使用" preferredStyle:UIAlertControllerStyleAlert];
                [self presentViewController:alert animated:YES completion:nil];
                [alert dismissViewControllerAnimated:YES completion:nil];

            }
        } andFailureBlock:^(NSError *error) {
            
        }];
        
    }else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入正确的电话号码" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:nil];
        [alert dismissViewControllerAnimated:YES completion:nil];

    }
    
}
//获取验证码倒计时
- (void)receiveCheckNumButton{
    __block int timeout=60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [_button setTitle:@"重新获取" forState:UIControlStateNormal];
                _button.userInteractionEnabled = YES;
                
            });
        }else{
            int seconds = timeout;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //让按钮变为不可点击的灰色
                _button.userInteractionEnabled = NO;
                //设置界面的按钮显示 根据自己需求设置
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [_button setTitle:[NSString stringWithFormat:@"%@秒后重新发送",strTime] forState:UIControlStateNormal];
                [UIView commitAnimations];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}
// 正则判断手机号码地址格式
- (BOOL)isMobileNumber:(NSString *)mobileNum {
    
    //    电信号段:133/153/180/181/189/177
    //    联通号段:130/131/132/155/156/185/186/145/176
    //    移动号段:134/135/136/137/138/139/150/151/152/157/158/159/182/183/184/187/188/147/178
    //    虚拟运营商:170
    
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[06-8])\\d{8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    return [regextestmobile evaluateWithObject:mobileNum];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [JYJMusicMiniView  shareMiniView].hidden = YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
